package com.zq.it.cms.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zq.it.cms.common.BaseService;
import com.zq.it.cms.common.security.CredentialsDigest;
import com.zq.it.cms.common.security.Digests;
import com.zq.it.cms.common.util.Encodes;
import com.zq.it.cms.domain.User;
import com.zq.it.cms.repository.UserRepository;

@Service
public class UserService extends BaseService<UserRepository, User>{

	private static final int SALT_SIZE = 8;
	
	@Autowired
	private CredentialsDigest credentialsDigest;

	public User findByUserName(String userName){
		return getRepository().findByUserName(userName);
	}
	
	/**
	 * 根据ID修改密码
	 */
	public User updatePassword(Long id, String password){
		User user = findById(id);
		if(user != null){
			byte[] saltBytes = Digests.generateSalt(SALT_SIZE);
	        String salt = Encodes.encodeHex(saltBytes);
	        user.setSalt(salt);
	        String encPass = credentialsDigest.digest(password, saltBytes);
	        user.setPassword(encPass);
	       return save(user);
		}
		return null;
	}
}
